﻿using System;
using Microsoft.Xna.Framework;

namespace ThreeDWorld
{
    public struct Orientation
    {
        public static Orientation Create()
        {
            Orientation o = new Orientation();

            o.World = Matrix.Identity;

            return o;
        }

        public Matrix World;

        public Vector3 Position
        {
            get { return World.Translation; }

            set { World.Translation = value; }
        }

        public Vector3 Right
        {
            get { return World.Right; }
        }

        public Vector3 Up
        {
            get { return World.Up; }
        }

        public Vector3 Forward
        {
            get { return World.Backward; }

            set
            {
                Vector3 f = Vector3.Normalize(value);
                Vector3 u = Vector3.UnitY;
                Vector3 r;
                float dot = Vector3.Dot(f, u);

                if (dot < -0.9999 || dot > 0.9999)
                {
                    u = Vector3.UnitX;
                }

                r = Vector3.Normalize(Vector3.Cross(u, f));
                u = Vector3.Normalize(Vector3.Cross(f, r));

                World.Right = r;
                World.Up = u;
                World.Backward = f;
            }
        }

        public void Rotate(float upAxisRadians)
        {
            Vector3 f = Forward;
            Matrix rot = Matrix.CreateRotationY(upAxisRadians);

            Forward = Vector3.TransformNormal(f, rot);
        }
    }
}
